(function(){
  $(function(){
    // 初始化明星商品
    getStarList();

    // 删除购物车商品
    $('body').on('click', '.js_cartDelete', function(){
      var skuLine = $(this).closest('tr');
      var skuId   =  parseInt(skuLine.data('sku_id'));
      var isPromotion = parseInt(skuLine.data('is_promotion'));
      var goodsId = skuLine.data('goods_id');
      var pay_account_id = $(this).closest('.cartPayClass').data('pay_account_id');
      //加入检测代码
      var s=s_gi(s_account);
      s.linkTrackVars="events,products";
      s.linkTrackEvents="scRemove";
      s.events="scRemove";
      s.products=";"+goodsId;
      s.tl(this,'o','shopping cart remove');

      if (btnClick() == false) {
        return false;
      }
      showConfirm('您确定要从购物车中删除该商品吗？', function(){
        deleteCart(skuId, isPromotion, pay_account_id, function(json){
          if (json.info == 'ok') {
            skuLine.remove();
            $('.js_cartCount_'+pay_account_id).html(json.count);
            $('.js_cartPromotionInfo').html(json.promotion);

            // 删除顶部商品数量
            $('.js_topCartList').find('dl').each(function(){
              var currSkuId = $(this).attr('data-sku_id');
              var currIsPromotion  = $(this).attr('data-is_promotion');
              if (currIsPromotion == 1 && skuId == currSkuId) {
                $(this).remove();
              }
            });

            if (json.has_express > 0) {
              $('.js_freeExpressPrice').html('还需 '+json.has_express+' 元在线支付免运费');
            } else {
              $('.js_freeExpressPrice').html('');
            }

            if (isPromotion > 0) {
              $('.js_relationUl').children('li').each(function(){
                var currSkuId        = $(this).attr('data-sku_id');
                //var currIsPromotion  = $(this).attr('data-goods_id');
                if (skuId == currSkuId) {
                  $(this).removeClass('current').find('.check-wrap').removeClass('checked');
                  $(this).attr('data-type', 'disabled');
                  $(this).attr('data-sku_id', 0);
                }
              });
            } else {
              /* 同级别赠品删除
              var hasGoods = 0;
              $('.js_cartListTable').find('tr').each(function(){
                var currGoodsId = $(this).data('goods_id');
                var currPromotion = $(this).data('is_promotion');
                if (currPromotion == 0 && currGoodsId == goodsId) {
                  hasGoods = 1;
                }
              });
              if (hasGoods == 0) {
                $('.js_isGift').each(function(){
                  var giftIds = $(this).data('gift_ids').split(',');
                  var giftNum = $(this).data('gift_num').split(',');
                  for (var i = 0; i < giftIds.length; i++) {
                    if (giftIds[i] == goodsId) {
                      var currNum = giftNum[i];
                      var oldNum  = $(this).find('.js_goodsNumTD').children('span').html()-0;
                      if (oldNum-currNum <= 0) {
                        $(this).remove();
                      } else {
                        $(this).find('.js_goodsNumTD').children('span').html(oldNum-currNum);
                      }
                    }
                  }
                });
              }*/
            }

            var num = parseInt(json.num);
            if (isNaN(num) || num == 0) {
              location.href = location.href;
            }

            $('.js_buyCartNumber').html(json.cart_num);
            // 重置明星商品
            getStarList();
          } else if(json.info == 'reload') {
            location.href = location.href;
          } else {
            showMsg(json.info, 'error');
          }
        });
      });
      btnClick('reset');
    });

    // 改变数量
    var oldSkuNum = 1;
    $('.js_cartListTable').on('focus', '.js_cartGoodsNum',function(){
      oldSkuNum = $(this).val();
    });
    $('.js_cartListTable').on('blur', '.js_cartGoodsNum',function(){
      var currTr  = $(this).closest('tr');
      var pay_account_id = $(this).closest('.cartPayClass').data('pay_account_id');
      if (currTr.hasClass('disabled')) {
        $(this).val(oldSkuNum);
        return false;
      }
      var input   = $(this);
      var stock   = currTr.data('stock');
      var currNum = input.val();
      var skuId   = currTr.data('sku_id');

      if (isNaN(currNum) || currNum < 1) {
        currNum = oldSkuNum;
      }
      // if (currNum > 200) {
      //   //currNum = 200;
      //   showMsg('商品数量不能大于200');
      //   $(this).val(oldSkuNum);
      //   return;
      // }
      if (currNum == 1) {
        $('.js_goodsNumSub').addClass('sub-disabled');
      } else {
        $('.js_goodsNumSub').removeClass('sub-disabled');
      }
      if (btnClick() == false) {
        return false;
      }
      editCart(skuId, currNum, 0, pay_account_id, function(json){
        if (json.info == 'ok') {
          $('.js_cartCount_'+pay_account_id).html(json.count);
          $('.js_cartPromotionInfo').html(json.promotion);
          currTr.find('.js_currCount').html(json.curr_count);
          input.val(currNum);

          currTr.find('.gift').each(function(){
            var giftNum = $(this).data('gift_num');
            $(this).find('em').html(giftNum*currNum);
          });

          if (json.has_express > 0) {
            $('.js_freeExpressPrice').html('还需 '+json.has_express+' 元在线支付免运费');
          } else {
            $('.js_freeExpressPrice').html('');
          }

          $('.js_buyCartNumber').html(json.cart_num);
        } else if(json.info == 'reload') {
          location.href = location.href;
        } else {
          showMsg(json.info, 'error');
          input.val(oldSkuNum);
        }
      });
    });

    // 数量+
    $('.js_cartListTable').on('click', '.js_goodsNumAdd',function(){
      var currTr  = $(this).closest('tr');
      var pay_account_id = $(this).closest('.cartPayClass').data('pay_account_id');
      if (currTr.hasClass('disabled')) {
        return false;
      }
      var stock   = currTr.data('stock');
      var skuId   = currTr.data('sku_id');
      var input   = $(this).prev();
      var currNum = parseInt(input.val());
      var oldNum  = currNum;
      currNum = parseInt(currNum) + 1;
      if (currNum == 0) {
        currNum = 1;
      }
      // if (currNum > 200) {
      //   //currNum = 200;
      //   showMsg('商品数量不能大于200');
      //   input.val(200);
      //   return;
      // }
      if (currNum > 1) {
        $('.js_goodsNumSub').removeClass('sub-disabled');
      }
      if (btnClick() == false) {
        return false;
      }
      editCart(skuId, currNum, 0, pay_account_id, function(json){
        if (json.info == 'ok') {
          $('.js_cartCount_'+pay_account_id).html(json.count);
          $('.js_cartPromotionInfo').html(json.promotion);
          currTr.find('.js_currCount').html(json.curr_count);
          input.val(currNum);

          currTr.find('.gift').each(function(){
            console.log($(this).data('gift_num'));
            var giftNum = $(this).data('gift_num');
            $(this).find('em').html(giftNum*currNum);
          });

          if (json.has_express > 0) {
            $('.js_freeExpressPrice').html('还需 '+json.has_express+' 元在线支付免运费');
          } else {
            $('.js_freeExpressPrice').html('');
          }

          $('.js_buyCartNumber').html(json.cart_num);
        } else if(json.info == 'reload') {
          location.href = location.href;
        } else {
          showMsg(json.info, 'error');
          input.val(oldNum);
        }
      });
    });

    // 数量 -
    $('.js_cartListTable').on('click', '.js_goodsNumSub',function(){
      var currTr  = $(this).closest('tr');
      var pay_account_id = $(this).closest('.cartPayClass').data('pay_account_id');
      if (currTr.hasClass('disabled')) {
        return false;
      }
      var stock   = currTr.data('stock');
      var skuId   = currTr.data('sku_id');
      var input   = $(this).next();
      var currNum = parseInt(input.val());
      var oldNum  = currNum;
      currNum = currNum - 1;
      if (currNum < 1) {
        currNum = 1;
      }
      if (currNum == 1) {
        $(this).addClass('sub-disabled');
      }
      if (btnClick() == false) {
        return false;
      }
      editCart(skuId, currNum, 0, pay_account_id, function(json){
        if (json.info == 'ok') {
          $('.js_cartCount_'+pay_account_id).html(json.count);
          $('.js_cartPromotionInfo').html(json.promotion);
          currTr.find('.js_currCount').html(json.curr_count);
          input.val(currNum);

          currTr.find('.gift').each(function(){
            var giftNum = $(this).data('gift_num');
            $(this).find('em').html(giftNum*currNum);
          });

          if (json.has_express > 0) {
            $('.js_freeExpressPrice').html('还需 '+json.has_express+' 元在线支付免运费');
          } else {
            $('.js_freeExpressPrice').html('');
          }

          $('.js_buyCartNumber').html(json.cart_num);
        } else if(json.info == 'reload') {
          location.href = location.href;
        } else {
          showMsg(json.info, 'error');
          input.val(oldNum);
        }
      });
    });

    // 添加 加价购
    var oldSlt;
    $('.js_sltDiscountGoods label').on('click', function(e){
      e.preventDefault();
      var that    = $(this).closest('li');
      var type    = that.attr('data-type');
      var id      = that.data('id');
      var slted   = that.attr('data-sku_id'); //已选择的sku_id
      var goodsId = that.data('goods_id');
      var skuNum  = that.data('sku_num');
      var skuId   = that.data('sku_ids');
      oldSlt      = that;
      var pay_account_id = $(this).closest('.cartPayClass').data('pay_account_id');
      if (btnClick() == false) {
        return false;
      }
      if (type != 'disabled') {
        deleteCart(slted, 1, pay_account_id, function(json){
          if (json.info == 'ok') {
            
            // 多个支付渠道
            if($('.js_subCart').length > 1) {
              window.location.reload();
              return;
            }
            
            $('.js_cartCount_'+pay_account_id).html(json.count);
            that.removeClass('current').find('.check-wrap').removeClass('checked');
            that.attr('data-type', 'disabled');
            that.attr('data-sku_id', 0);

            // 删除上方tr
            $('.js_cartListTable').find('tr').each(function(){
              var currSkuId = parseInt($(this).attr('data-sku_id'));
              var currIsPromotion  = $(this).attr('data-is_promotion');
              if (currIsPromotion == 1 && slted == currSkuId) {
                $(this).remove();
              }
            });
            $('.js_topCartList').find('dl').each(function(){
              var currSkuId = $(this).attr('data-sku_id');
              var currIsPromotion  = $(this).attr('data-is_promotion');
              if (currIsPromotion == goodsId && skuId == currSkuId) {
                $(this).remove();
              }
            });

            if (json.has_express > 0) {
              $('.js_freeExpressPrice').html('还需 '+json.has_express+' 元在线支付免运费');
            } else {
              $('.js_freeExpressPrice').html('');
            }

            $('.js_buyCartNumber').html(json.cart_num);
          } else if(json.info == 'reload') {
            location.href = location.href;
          }
          btnClick('reset');
        });
        return;
      }

      if (skuNum == 1) {
        addGoodsToCart(skuId, 1, function(json){
          // 多个支付渠道
          if($('.js_subCart').length > 1) {
            window.location.reload();
            return;
          }
          
          oldSlt.attr('data-sku_id', skuId);
          oldSlt.addClass('current').find('.check-wrap').addClass('checked');
          oldSlt.attr('data-type', 'enabled');
          $('.js_cartCount_'+pay_account_id).html(json.count);
          $('.js_cartPromotionInfo').html(json.promotion);
          $('.js_cartListTable').append(json.data);
          viewTable();

          $('.js_buyCartNumber').html(json.cart_num);
          btnClick('reset');
        }, 1);
        return;
      }

      var url = siteUrl+'/cart/get_promotion_add_list';
      $.post(url, { id:id, slted_sku_id:slted }, function(data){
        if (data.info == 'ok') {
          $('.js_sltSkuDiv').html(data.data);
          $('.float-sel-colors .list li:nth-child(3n)').css('margin-right','0');
          var divH    = $('.js_sltSkuDiv').innerHeight();
          var divW    = $('.js_sltSkuDiv').width();
          var screenH = $(window).height();
          var screenW = $(window).width();
          var top     = (screenH-divH)/2+$(window).scrollTop();
          var left    = (screenW-divW)/2;
          //console.log($('.js_sltSkuDiv').innerHeight());
          //top         = $(window).scrollTop();
          $('.js_sltSkuDiv').css({ position:'absolute', top:top+'px', margin:'0px', left:left+'px' });
          $('.js_sltSkuDiv').show().prev().show();
        } else {
          showMsg(data.info, 'error');
        }
        btnClick('reset');
      }, 'json');
    });

    // 选择商品
    $('.js_sltSkuDiv').on('click', '.js_sltRelationSku', function(){
      var skuId = $(this).data('sku_id');
      $(this).addClass('current').find('span').addClass('checked');
      $(this).siblings().each(function(){
        $(this).removeClass('current').find('span').removeClass('checked');
      });
      $('.js_addCartRelation').attr('data-sku_id', skuId).removeClass('disabled');
    });

    // 隐藏弹层
    $('body').on('click', '.js_sltSkuDivBG', function(){
      $('.js_sltSkuDiv').hide();
      $(this).addClass('hidden');
    });

    // 添加到购物车
    $('.js_sltSkuDiv').on('click', '.js_addCartRelation,.js_closeDiv', function(){
      var skuId   = $('.js_addCartRelation').attr('data-sku_id');
      var type    = $(this).data('type');
      if (type == 'close') {
        oldSlt.removeClass('current').find('.check-wrap').removeClass('checked');
        oldSlt.attr('data-type', 'disabled');
        oldSlt.attr('data-sku_id', 0);
      } else {
        if (btnClick() == false ) {
          return false;
        }
        addGoodsToCart(skuId, 1, function(json){
          // 多个支付渠道
          if($('.js_subCart').length > 1) {
            window.location.reload();
            return;
          }
          oldSlt.attr('data-sku_id', skuId);
          oldSlt.addClass('current').find('.check-wrap').addClass('checked');
          oldSlt.attr('data-type', 'enabled');
          $('.js_cartCount').html(json.count);
          $('.js_cartPromotionInfo').html(json.promotion);
          $('.js_cartListTable').append(json.data);
          viewTable();

          $('.js_buyCartNumber').html(json.cart_num);
          btnClick('reset');
        }, 1);
      }

      $('.js_sltSkuDiv').hide().prev().hide();
    });

    // 添加明星商品到购物车
    $('.js_starGoodsList').on('click', '.js_addStarGoodsToCart', function(){
      var skuId   = $(this).data('sku_id');
      var that    = $(this);
      addGoodsToCart(skuId, 1, function(json){
        $('.js_cartCount').html(json.count);
        $('.js_cartPromotionInfo').html(json.promotion);
        showMsg('添加成功', 'success', 100);
        $.scrollTo('#container', 400);

        var inCart = 0;
        $('.js_cartListTable').find('tr').each(function(){
          var currSkuId = $(this).attr('data-sku_id');
          var isPromotion = $(this).attr('data-is_promotion');

          if (skuId == currSkuId && isPromotion == 0) {
            var currNum = $(this).find('js_cartGoodsNum').val()-0;
            $(this).find('js_cartGoodsNum').val(currNum+1);
            inCart = 1;
          }
        });
        if (inCart == 0) {
          $('.js_cartListTable').find('tr').eq(0).after(json.data);
          viewTable();
        }

        // 重置明星商品
        getStarList();

        $('.js_buyCartNumber').html(json.cart_num);
      });
    });

    // 提交购物车
    $('.js_subCart').on('click', function(){
      var allowSub = 1;
      $('.js_cartListTable').find('tr').each(function(){
        if ($(this).hasClass('disabled')) {
          allowSub = 0;
          showMsg('购物车的有的商品库存不够了，请修改后提交');
          return;
        }
      });
      if (allowSub == 1) {
        var toLink = $(this).data('href')
        checkLogin(toLink, function(){
          location.href = toLink;
        });
      }
    });

    // 自动缩放图片
    $(window).resize(function(){
      var maxW = $('.js_hotGoodsList').width();
      var maxH = $('.js_hotGoodsList').height();
      imageCenters($('.js_hotGoodsList'), maxW, maxH);
    });
  });

  function viewTable()
  {
    $('.tab-buy-car tr.disabled td').css('color','#c8c8c8');
    $('.tab-buy-car td:last-child').css({ 'text-align':'center' });
  }

  // 修改购物车
  function editCart(skuId, goodsNum, isPromotion, pay_account_id, callback)
  {
    var url = siteUrl + '/cart/modify_cart_num';
    $.post(url, { goods_num:goodsNum, sku_id:skuId, is_promotion:isPromotion, pay_id:pay_account_id }, function(data){
      if (callback) {
        callback(data);
      }
      btnClick('reset');
    }, 'json');
  }

  // 删除购物车商品
  function deleteCart(skuId, isPromotion, pay_account_id, callback)
  {
    var url = siteUrl + '/cart/delete_cart';
    $.post(url, { sku_id:skuId, is_promotion:isPromotion, pay_id:pay_account_id }, function(json){
      if (callback) {
        callback(json);
      }
      btnClick('reset');
    }, 'json');
  }

  function getStarList()
  {
    var url = siteUrl+'/cart/get_star_list';
    $.get(url, { }, function(json){
      if (json.info == 'ok') {
        $('.js_starGoodsList').html(json.data);
        var maxW = $('.js_hotGoodsList').width();
        var maxH = $('.js_hotGoodsList').height();
        imageCenters($('.js_hotGoodsList'), maxW, maxH);
      }
      btnClick('reset');
    }, 'json');
  }
})();